package com.ifonly.activerecord;

import java.lang.reflect.Modifier;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ifonly
 * @version 1.0 2016-01-11 13:53
 * @since JDK 1.6
 */
public class ActiveRecordFactory {
    private static ModelMapper modelMapper = Db.getInstance().getModelMapper();;

    private static final ReentrantLock LOCK = new ReentrantLock();

    public static <T extends Model> T getActiveRecord(Class<T> clazz) {
        if (!Model.class.isAssignableFrom(clazz)) {
            throw new IllegalArgumentException("Provide class must implemented Model: " + clazz.getName());
        }
        if (Modifier.isInterface(clazz.getModifiers()) || Modifier.isAbstract(clazz.getModifiers())) {
            throw new IllegalArgumentException("Provide class must not a abstract class or a interface: " + clazz.getName());
        }

        T t = modelMapper.getModel(clazz);
        if (t != null) {
            return t;
        }
        LOCK.lock();
        try {
            modelMapper.addModelMapper(clazz);
            return modelMapper.getModel(clazz);
        } finally {
            LOCK.unlock();
        }
    }

}
